import React, { useContext, useState } from "react"

interface ThemeContextType {
  isLight: boolean,
  setIsLight: (value: boolean) => void
}

const ThemeContext = React.createContext({} as ThemeContextType)


const Child2 = () => {
  const context = useContext(ThemeContext)
  const style = {
    width: '150px',
    height: '150px',
    backgroundColor: context.isLight ? '#fff' : '#000',
    color: context.isLight ? '#000' : '#fff',
    border: '10px solid green'
  }
  return <>
    <div style={style}>
      <div>孙子组件</div>
      <button onClick={() => context.setIsLight(!context.isLight)}>切换主题</button>
    </div>
  </>
}

const Child = () =>{
  const context = useContext(ThemeContext)
  const style = {
    width: '300px',
    height: '300px',
    backgroundColor: context.isLight ? '#fff' : '#000',
    color: context.isLight ? '#000' : '#fff',
    border: '10px solid red',
    display: 'flex',
    flexDirection: 'column' as const,
    justifyContent: 'center' as const,
    alignItems: 'center' as const
  }
  return <>
    <div style={style}>
      <h1>子组件</h1>
      <Child2 />
    </div>
  </>
}

export default function Demo09() {
  const [isLight, setIsLight] = useState(true)
  return (<>
    <h1>useContext示例</h1>
    <button onClick={() => setIsLight(!isLight)}>{isLight ? '浅色模式' : '深色模式'}</button>
    <ThemeContext value={{ isLight, setIsLight}}>
      <Child />
    </ThemeContext>
  </>)
}